KONA_DIR := `realpath .`
KONA_VERSION := `jq -r .version ./version.json`
KONA_PRESTATE_HASH := `jq -r .prestateHash ./version.json`
KONA_INTEROP_PRESTATE_HASH := `jq -r .interopPrestateHash ./version.json`

default: build-all

build-all: build-prestates build-kona-host

build-prestates: build-cannon-prestate build-interop-prestate

build-cannon-prestate:
    @just build-prestate kona-client {{KONA_PRESTATE_HASH}}

build-interop-prestate:
    @just build-prestate kona-client-int {{KONA_INTEROP_PRESTATE_HASH}}

build-prestate VARIANT HASH:
    #!/usr/bin/env bash
    set -euo pipefail

    cd "{{KONA_DIR}}"
    # Check if required prestate already exists
    if [[ -f "prestates/{{HASH}}.bin.gz" ]]; then
        echo "Prestate {{HASH}} for variant {{VARIANT}} already exists"
        exit
    fi
    echo "Building prestate..."
    just checkout-kona
    cd "{{KONA_DIR}}/build/kona"
    cd docker/fpvm-prestates
    # Delete any existing artifacts (they're in .gitignore so reset --hard won't delete them)
    rm -rf ../../prestate-artifacts-cannon
    echo just cannon {{VARIANT}} "kona-client/v{{KONA_VERSION}}" $(cat ../../.config/cannon_tag)
    just cannon {{VARIANT}} "kona-client/v{{KONA_VERSION}}" $(cat ../../.config/cannon_tag)

    # Check the prestate hash matches what we expect
    ACTUAL_HASH=$(jq -r .pre ../../prestate-artifacts-cannon/prestate-proof.json)
    if [[ "${ACTUAL_HASH}" != "{{HASH}}" ]]; then
      echo "Incorrect prestate hash, expected {{HASH}} but was ${ACTUAL_HASH}"
      exit 1
    fi

    mkdir -p "{{KONA_DIR}}/prestates"
    cp ../../prestate-artifacts-cannon/prestate.bin.gz "{{KONA_DIR}}/prestates/{{HASH}}.bin.gz"

build-kona-host:
    #!/usr/bin/env bash
    set -euo pipefail

    # Check if kona-host has already been built
    # This is a simplistic check that relies on CircleCI's cache being keyed on this file
    # which contains the kona version we're checking out. Locally you may need to run
    # just clean to force a rebuild if the kona version has changed.
    if [[ -f "bin/kona-host" ]]; then
        echo "kona-host already built. Assuming it is built from kona-client/v{{KONA_VERSION}}"
        exit
    fi

    echo "Building kona-host"
    just checkout-kona
    cd "{{KONA_DIR}}/build/kona"
    just build-native --bin kona-host

    mkdir -p "{{KONA_DIR}}/bin"
    cp "{{KONA_DIR}}/build/kona/target/debug/kona-host" "{{KONA_DIR}}/bin/kona-host"

checkout-kona:
    #!/usr/bin/env bash
    set -euo pipefail

    DIR="{{KONA_DIR}}/build"
    mkdir -p "${DIR}"
    cd "${DIR}"
    if [[ -d kona ]]; then
      cd kona
      git fetch origin
      git checkout -f "kona-client/v{{KONA_VERSION}}"
      git reset --hard HEAD
    else
      git clone -b "kona-client/v{{KONA_VERSION}}" https://github.com/op-rs/kona kona
      cd kona
    fi

clean:
  #!/usr/bin/env bash
  set -euo pipefail
  rm -rf "{{KONA_DIR}}/build" "{{KONA_DIR}}/prestates" "{{KONA_DIR}}/bin"
